import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Myorder from '@/views/Myorder'
import Layout from '@/views/Layout'
import Pay from '@/views/Pay'
import Search from '@/views/Search'
import SearchList from '@/views/Search/SearchList.vue'
import ProDetail from '@/views/Prodetail'
import { getInfo } from '@/utils/storage'

const Home = () => import('@/views/Layout/home.vue')
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: 'layout/home' },
    {
      path: '/layout',
      component: Layout,
      // 默认路由
      redirect: '/layout/home',
      children: [
        { path: 'home', component: Home },
        { path: 'category', component: () => import('@/views/Layout/category.vue') },
        { path: 'cart', component: () => import('@/views/Layout/cart.vue') },
        { path: 'user', component: () => import('@/views/Layout/user.vue') }
      ]
    },
    { path: '/login', component: Login },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    { path: '/search', component: Search },
    { path: '/searchList', component: SearchList },
    { path: '/prodetail/:goodsId', component: ProDetail, props: true }

  ]
})

// 定义一个数组进行存放需要权限进行访问的界面
const whiteList = ['/pay', '/myorder']
// 路由守卫
router.beforeEach((to, from, next) => {
  // 进行判断要进行访问的路径是否存在于白名单中
  const exist = whiteList.includes(to.path)
  console.log(exist)
  // 如果不存在于数组当中直接的进行放行
  if (!exist) {
    next()
  }

  // 存在于数组当中，进行判断本地token是否存在\
  const token = getInfo().token
  console.log(token)
  if (token === '') next('/login')
  next()
})

export default router
